package com.ruoyi.detail.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.detail.mapper.DetailMapper;
import com.ruoyi.detail.domain.Detail;
import com.ruoyi.detail.service.IDetailService;

/**
 * 明细Service业务层处理
 * 
 * @author ucu
 * @date 2024-05-04
 */
@Service
public class DetailServiceImpl implements IDetailService 
{
    @Autowired
    private DetailMapper detailMapper;

    /**
     * 查询明细
     * 
     * @param id 明细主键
     * @return 明细
     */
    @Override
    public Detail selectDetailById(Long id)
    {
        return detailMapper.selectDetailById(id);
    }

    /**
     * 查询明细列表
     * 
     * @param detail 明细
     * @return 明细
     */
    @Override
    public List<Detail> selectDetailList(Detail detail)
    {
        return detailMapper.selectDetailList(detail);
    }

    /**
     * 新增明细
     * 
     * @param detail 明细
     * @return 结果
     */
    @Override
    public int insertDetail(Detail detail)
    {
        return detailMapper.insertDetail(detail);
    }

    /**
     * 修改明细
     * 
     * @param detail 明细
     * @return 结果
     */
    @Override
    public int updateDetail(Detail detail)
    {
        return detailMapper.updateDetail(detail);
    }

    /**
     * 批量删除明细
     * 
     * @param ids 需要删除的明细主键
     * @return 结果
     */
    @Override
    public int deleteDetailByIds(Long[] ids)
    {
        return detailMapper.deleteDetailByIds(ids);
    }

    /**
     * 删除明细信息
     * 
     * @param id 明细主键
     * @return 结果
     */
    @Override
    public int deleteDetailById(Long id)
    {
        return detailMapper.deleteDetailById(id);
    }

    @Override
    public int deleteDetailByIdWithUserId(Long[] ids) {
        // 判断是否是用户自己的明细数据

        // 使用 ArrayList 来存储匹配的 ID
        List<Long> userIds = new ArrayList<>();

        for (Long id : ids) {
            Detail detail = detailMapper.selectDetailById(id);
            // 检查明细是否存在且用户 ID 不为空，并且与当前用户 ID 匹配
            if (detail != null && detail.getUserId() != null && detail.getUserId().equals(SecurityUtils.getUserId())) {
                userIds.add(id);
            }
        }
        // 将 List 转换为数组
        Long[] userIdArray = userIds.toArray(new Long[0]);

        // 删除匹配的 ID
        return detailMapper.deleteDetailByIds(userIdArray);

    }

    @Override
    public boolean hasDuplicateWithSeasonAndNameTwo(Long userId) {
        return detailMapper.hasDuplicateWithSeasonAndNameTwo(userId);
    }
}
